package com.mamingchao.springcloud.eureka.Interceptor;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by mamingchao on 2020/9/10.
 */
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

        System.out.println("RestTemplateInterceptor http request--" + ToStringBuilder.reflectionToString(httpRequest));
        System.out.printf("RestTemplateInterceptor http request body--",ToStringBuilder.reflectionToString(bytes));

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 0;
            }

            @Override
            public String getStatusText() throws IOException {
                return "RestTemplateInterceptor status text";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new InputStream() {
                    /**
                     * Reads the next byte of data from the input stream. The value byte is
                     * returned as an <code>int</code> in the range <code>0</code> to
                     * <code>255</code>. If no byte is available because the end of the stream
                     * has been reached, the value <code>-1</code> is returned. This method
                     * blocks until input data is available, the end of the stream is detected,
                     * or an exception is thrown.
                     * <p>
                     * <p> A subclass must provide an implementation of this method.
                     *
                     * @return the next byte of data, or <code>-1</code> if the end of the
                     * stream is reached.
                     * @throws IOException if an I/O error occurs.
                     */
                    @Override
                    public int read() throws IOException {
                        return 0;
                    }
                };
            }

            @Override
            public HttpHeaders getHeaders() {
                return new HttpHeaders();
            }
        };
    }
}
